﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ImmovablesManager
{
    /// <summary>
    /// Interaction logic for FlatCard.xaml
    /// </summary>
    public partial class FlatCard : Window
    {
        private Guid _realtorId;
        private string _cardNumber;
        private Guid _flatId;
        private bool _isEdit;
        private Guid _flatNewGuid;
        //public FlatCard()
        //{
        //    InitializeComponent();
        //    OpenCardViewFill();


        //    _realtorId = Login.UserId; 
        //    var currentRealtorName = Login.UserName;
        //    TBxRealtor.Text = currentRealtorName;
        //    TBxRealtor.IsReadOnly = true;
        //}

        public FlatCard(Guid flatId, bool isEdit)
        {
            InitializeComponent();

            _realtorId = Login.UserId;
            _isEdit = isEdit;

            var currentRealtorName = Login.UserName;

            TBxRealtor.Text = currentRealtorName;
            TBxRealtor.IsReadOnly = true;

            OpenCardViewFill();

            if(isEdit)
            {
                _flatId = flatId;
                FillFields();
                _flatNewGuid = AddFlat(false);
            }
        }


        public void FillComboBox(ComboBox comboBox, Guid tag)
        {
            foreach (var item in comboBox.Items)
            {
                var it = item as ComboBoxItem;
                if (Guid.Parse(it.Tag.ToString()) == tag)
                {
                    comboBox.SelectedIndex = comboBox.Items.IndexOf(it);
                }
            }
        }

        
        private void FillFields()
        {
            var currentFlat = AppController.ImmoRepository.GetFlatById(_flatId);

            AppController.ImmoRepository.AddChangingStory("Начало редактирования карты вторичного жилья",
                                               currentFlat.FlatId, "", "", _realtorId, "edit", currentFlat.FinancialData.FnancialDataContract);
            objectTBx.Text = currentFlat.FlatObject;
            FlatAddressTBx.Text = currentFlat.FlatAddress;

            FillComboBox(FlatRegionComboBx, currentFlat.FlatRegionId);
            FillComboBox(FlatTypeComboBox, currentFlat.FlatTypeId);
            FillComboBox(FlatWCCombox, currentFlat.FlatWCId);
            FillComboBox(FlatSellsTermsBx, currentFlat.FlatSellTermsId);
            FillComboBox(FlatHouseMaterialComboBx, currentFlat.FlatHouseMaterial);
            FillComboBox(FlatBalconComboBx, currentFlat.FlatBalconId);

            if (currentFlat.FlatRoomsToSell != null)
                FlatRoomsToSellTBx.SelectedIndex = (int)currentFlat.FlatRoomsToSell - 1;
            if (currentFlat.FlatRoomCount != null)
                FlatRoomsCountTBx.SelectedIndex = (int)currentFlat.FlatRoomCount - 1;

            ShowDateCalendarBtn.Value = currentFlat.FlatShowTime;
            FinDateDate.SelectedDate = currentFlat.FinancialData.FinancialDataDate;

            FlatNearestSignsTBx.Text = currentFlat.FlatNearestSigns;
            ShowTermsBx.Text = currentFlat.FlatShowTerms;

            FlatTotalAreaTBx.Text = currentFlat.FlatTotalArea.ToString();
            FlatLivingAreaTBx.Text = currentFlat.FlatLivingArea.ToString();
            FlatKitchenAreaTBx.Text = currentFlat.FlatKitchenArea.ToString();

            FlatRoomPlaningTypeCheckBx.IsChecked = currentFlat.FlatRoomAppointment;
            FlatFloorTBx.Text = currentFlat.FlatFloor.ToString();
            FlatFloorsTBx.Text = currentFlat.FlatFloors.ToString();

            FlatWindowsViewTBx.Text = currentFlat.FlatWindowsView;
            FlatBoilerPositionTBx.Text = currentFlat.FlatBoilerPosition;

            DocumentsTBx.Text = currentFlat.FlatDocumentsReady;
            MortgageCheckBx.IsChecked = currentFlat.FlatMortgage;

            AdditionalIfrormationTBx.Text = currentFlat.FlatAdditionalInformation;

            HasPhoneChBx.IsChecked = currentFlat.FlatTelephone;
            NeighboursCountTBx.Value = currentFlat.FlatNeighboursCount;
            NeighBoursPensioneersCount.Value = currentFlat.FlatNeighboursPensioneersCount;
            NeighboursWithChildrenCountTBx.Value = currentFlat.FlatNeighboursChildrenCount;

            TBxSource.Text = currentFlat.FinancialData.FinancialDataSource;

            TBxCardNumber.Text = currentFlat.FinancialData.FinancialDataCardNumber.ToString();
            TBxRealtor.Text = currentFlat.FinancialData.User.UserFirstName;
            TBxContractNumber.Text = currentFlat.FinancialData.FnancialDataContract;
            

            TBxCost.Text = currentFlat.FinancialData.FinancialDataPriceWithUs.ToString();
            FIOOwnerBx.Text = currentFlat.Owner.OwnerName;
            PhoneOwnerBx.Text = currentFlat.Owner.OwnerMobilePhone;
            PhoneOwnerAddBx.Text = currentFlat.Owner.OwnerHomePhone;

            FlatHowToGetByPubTransportTBx.Text = currentFlat.FlatHowToGetByPubTransport;

        }

        private void BTnOk_Click(object sender, RoutedEventArgs e)
        {
            if (!_isEdit)
            {
                AddFlat(true);
            }
            else
            {
                EditFlat();
            }
            Close();
        }

        private void BTnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        public void OpenCardViewFill()
        {
            foreach (var region in AppController.ImmoRepository.GetAllRegions())
            {
                FlatRegionComboBx.Items.Add(new ComboBoxItem() { Content = region.RegionName, Tag = region.RegionId });//, Name = region.RegionId.ToString()});
            };
            FlatRegionComboBx.SelectedIndex = 0;


            foreach (var typeWC in AppController.ImmoRepository.GetAllWCType())
            {
                FlatWCCombox.Items.Add(new ComboBoxItem() { Content = typeWC.WCTypeName, Tag = typeWC.WCId });
            }
            FlatWCCombox.SelectedIndex = 0;

            foreach (var terms in AppController.ImmoRepository.GetAllSellTerms())
            {
                FlatSellsTermsBx.Items.Add(new ComboBoxItem() { Content = terms.SellTermsName, Tag = terms.SellTermsId});
            }
            FlatSellsTermsBx.SelectedIndex = 0;

            foreach (var typeWall in AppController.ImmoRepository.GetAllHouseMaterial())
            {
                FlatHouseMaterialComboBx.Items.Add(new ComboBoxItem() { Content = typeWall.HouseMaterialName, Tag = typeWall.HouseMaterialId });
            }
            FlatHouseMaterialComboBx.SelectedIndex = 0;

            foreach (var typeFlat in AppController.ImmoRepository.GetAllFlatType())
            {
                FlatTypeComboBox.Items.Add(new ComboBoxItem() { Content = typeFlat.FlatTypeName, Tag = typeFlat.FlatTypeId });
            }
            FlatTypeComboBox.SelectedIndex = 0;
            
            
            foreach (var balcon in AppController.ImmoRepository.GetAllBalconType())
            {
                FlatBalconComboBx.Items.Add(new ComboBoxItem() { Content = balcon.BalconTypeName, Tag = balcon.BalconTypeId });
            }
            FlatBalconComboBx.SelectedIndex = 0;


            FinDateDate.SelectedDate = DateTime.Now;
            FlatTotalAreaTBx.Text = 0.ToString();
            FlatLivingAreaTBx.Text = 0.ToString();
            FlatKitchenAreaTBx.Text = 0.ToString();
            FlatRoomsCountTBx.Text = 1.ToString();
            FlatRoomsToSellTBx.Text = 1.ToString();
            FlatFloorTBx.Text = 1.ToString();
            FlatFloorsTBx.Text = 10.ToString();
            ShowDateCalendarBtn.Text = DateTime.Now.ToString();
            TBxCost.Text = 0.ToString();
        }

        public Guid AddFlat(bool isShown)
        {

            Guid ownerId = AppController.ImmoRepository.AddOwner(PhoneOwnerBx.Text, PhoneOwnerAddBx.Text, FIOOwnerBx.Text);

            Guid finDataId = AppController.ImmoRepository.AddFinancialData(FinDateDate.SelectedDate,
                                                                            double.Parse(TBxCost.Text), 
                                                                            0, 
                                                                            _realtorId, TBxContractNumber.Text, 
                                                                            TBxSource.Text);
            _cardNumber = AppController.ImmoRepository.GetFinancialDataById(finDataId).FinancialDataCardNumber.ToString();

            Guid flatSellsTermsBx = (Guid)((ComboBoxItem)FlatSellsTermsBx.SelectedItem).Tag;
            Guid flatTypeComboBox = (Guid)((ComboBoxItem)FlatTypeComboBox.SelectedItem).Tag;
            Guid currentWCType = (Guid)((ComboBoxItem)FlatWCCombox.SelectedItem).Tag;
            Guid flatBalconComboBx = (Guid)((ComboBoxItem)FlatBalconComboBx.SelectedItem).Tag;
            Guid flatHouseMaterialComboBx = (Guid)((ComboBoxItem)FlatHouseMaterialComboBx.SelectedItem).Tag;
            Guid flatRegionComboBx = (Guid)((ComboBoxItem)FlatRegionComboBx.SelectedItem).Tag;

              var flatId =  AppController.ImmoRepository.AddFlat(AdditionalIfrormationTBx.Text, flatBalconComboBx, FlatAddressTBx.Text,
                   FlatBoilerPositionTBx.Text, DocumentsTBx.Text,finDataId, int.Parse(FlatFloorTBx.Text),int.Parse(FlatFloorsTBx.Text), flatHouseMaterialComboBx,
                   double.Parse(FlatKitchenAreaTBx.Text), double.Parse(FlatTotalAreaTBx.Text), double.Parse(FlatLivingAreaTBx.Text), objectTBx.Text,
                   flatRegionComboBx, MortgageCheckBx.IsChecked, FlatNearestSignsTBx.Text,ownerId, "", int.Parse(FlatRoomsCountTBx.Text),
                   int.Parse(FlatRoomsToSellTBx.Text), flatSellsTermsBx, NeighboursCountTBx.Value, 
                   NeighboursWithChildrenCountTBx.Value, NeighBoursPensioneersCount.Value, ShowTermsBx.Text, DateTime.Parse(ShowDateCalendarBtn.Text),
                   true, flatTypeComboBox, double.Parse(FlatTotalAreaTBx.Text), 0,currentWCType, "", FlatWindowsViewTBx.Text,
                   FlatHowToGetByPubTransportTBx.Text,
                   FlatRoomPlaningTypeCheckBx.IsChecked, "",
                   isShown);

              if (!isShown)
              {
                  AppController.ImmoRepository.AddChangingStory("Добавление карты вторичного жилья", flatId, "", "",
                                                                Login.UserId, "add", _cardNumber);
              }

            return flatId;
        }

        private void EditFlat()
        {
            var flat = AppController.ImmoRepository.GetFlatById(_flatId);

                string flatName = objectTBx.Text;
                string address = FlatAddressTBx.Text;

                Guid currentRegion = (Guid) ((ComboBoxItem) FlatRegionComboBx.SelectedItem).Tag;
                string currentRegionStr = (string) ((ComboBoxItem) FlatRegionComboBx.SelectedItem).Content;

                string nearestLandmarks = FlatNearestSignsTBx.Text;
                DateTime showTime = (DateTime) ShowDateCalendarBtn.Value;

                int roomCount = int.Parse(((ComboBoxItem) FlatRoomsCountTBx.SelectedItem).Tag.ToString());
                int roomToSellCount = int.Parse(((ComboBoxItem) FlatRoomsToSellTBx.SelectedItem).Tag.ToString());

                double totalArea = double.Parse(FlatTotalAreaTBx.Text);
                double kitchenArea = double.Parse(FlatKitchenAreaTBx.Text);
                double livingArea = double.Parse(FlatLivingAreaTBx.Text);

                Guid flatType = (Guid) ((ComboBoxItem) FlatTypeComboBox.SelectedItem).Tag;
                string flatTypeStr = (string) ((ComboBoxItem) FlatTypeComboBox.SelectedItem).Content;

                Guid wc = (Guid) ((ComboBoxItem) FlatWCCombox.SelectedItem).Tag;
                string wcTypeStr = (string) ((ComboBoxItem) FlatWCCombox.SelectedItem).Content;


                bool planing = (bool) FlatRoomPlaningTypeCheckBx.IsChecked;
                int floor = int.Parse(FlatFloorTBx.Text);
                int maxFloors = int.Parse(FlatFloorsTBx.Text);

                Guid houseMaterial = (Guid) ((ComboBoxItem) FlatHouseMaterialComboBx.SelectedItem).Tag;
                string houseMaterialStr = (string) ((ComboBoxItem) FlatHouseMaterialComboBx.SelectedItem).Content;

                string windows = FlatWindowsViewTBx.Text;
                string boilerPosition = FlatBoilerPositionTBx.Text;

                Guid balconType = (Guid) ((ComboBoxItem) FlatBalconComboBx.SelectedItem).Tag;
                string balconTypeStr = (string) ((ComboBoxItem) FlatBalconComboBx.SelectedItem).Content;


                Guid sellTerms = (Guid) ((ComboBoxItem) FlatSellsTermsBx.SelectedItem).Tag;
                string sellTermsStr = (string) ((ComboBoxItem) FlatSellsTermsBx.SelectedItem).Content;
                string showTerms = ShowTermsBx.Text;


                string documentsReady = DocumentsTBx.Text;
                bool mortgage = (bool) MortgageCheckBx.IsChecked;
                string mortgageStr = "Ипотека";


                string additionalInfo = AdditionalIfrormationTBx.Text;

                int cardNumber = int.Parse(TBxCardNumber.Text);

                var currentDate = (DateTime) FinDateDate.SelectedDate;
                string contract = TBxContractNumber.Text;
                string source = TBxSource.Text;
                double price = double.Parse(TBxCost.Text);


                string ownerFIO = FIOOwnerBx.Text;
                string ownerPhone = PhoneOwnerBx.Text;
                string ownerAdditionalPhone = PhoneOwnerAddBx.Text;

                string howToGetByPublicTransport = FlatHowToGetByPubTransportTBx.Text;

                int neighboursCount = (int)NeighboursCountTBx.Value;
                int neighboursWithChildrenCount = (int)NeighboursWithChildrenCountTBx.Value;
                int newighboursPensioneersCount = (int)NeighBoursPensioneersCount.Value;

                bool hasPhone = (bool)HasPhoneChBx.IsChecked;
            // запись в историю
            string number = flat.FinancialData.FinancialDataCardNumber.ToString();

            AddRecordChangingStory("Начало редактирования карточки", "", "", "edit", number);

            if (flatType != flat.FlatTypeId) AddRecordChangingStory("Изменение типа квартиры", flatTypeStr, flat.FlatType.FlatTypeName, "edit field", number);
            if (balconType != flat.FlatBalconId) AddRecordChangingStory("Изменение поля <балкон/лоджия>", balconTypeStr, flat.BalconType.BalconTypeName, "edit field", number);
            if (wc != flat.FlatWCId) AddRecordChangingStory("Изменение поля <Санузел>", wcTypeStr, flat.WCType.WCTypeName, "edit field", number);
            if (currentRegion != flat.FlatRegionId) AddRecordChangingStory("Изменение поля <район>", currentRegionStr, flat.Region.RegionName, "edit field", number);
            if (roomCount != flat.FlatRoomCount) AddRecordChangingStory("Изменение поля <Количество комнат>", roomCount.ToString(), flat.FlatRoomCount.ToString(), "edit field", number);
            if (houseMaterial != flat.FlatHouseMaterial) AddRecordChangingStory("Изменение поля <Материал стен>", 
                houseMaterialStr, flat.HouseMaterial.HouseMaterialName, "edit field", number);
            
            if (totalArea != flat.FlatTotalArea) AddRecordChangingStory("Изменение поля <Общая площадь>",
                totalArea.ToString(), 
                flat.FlatTotalArea.ToString(), 
                "edit field", number);
            if (livingArea != flat.FlatLivingArea) AddRecordChangingStory("Изменение поля <Жилая площадь>", 
                livingArea.ToString(),
                flat.FlatLivingArea.ToString(), "edit field",
                number);
            if (kitchenArea != flat.FlatKitchenArea) 
                AddRecordChangingStory("Изменение поля <Площадь кухни>", kitchenArea.ToString(), flat.FlatKitchenArea.ToString(), "edit field", number);

            if (ownerPhone != flat.Owner.OwnerMobilePhone) 
                AddRecordChangingStory("Изменение поля <Номер телефона владельца>", ownerPhone, 
                    flat.Owner.OwnerMobilePhone, "edit field", number);

            if (additionalInfo != flat.FlatAdditionalInformation) 
                AddRecordChangingStory("Изменение поля <Дополнительные сведения>", additionalInfo, flat.FlatAdditionalInformation,
                    "edit field", number);
            if (address != flat.FlatAddress)
                AddRecordChangingStory("Изменение поля <Адрес>", address, flat.FlatAddress, "edit field", number);
            if (documentsReady != flat.FlatDocumentsReady)
                AddRecordChangingStory("Изменение поля <Документы>", documentsReady, flat.FlatDocumentsReady, "edit field", number);
            if (flatName != flat.FlatObject) 
                AddRecordChangingStory("Изменение поля <Наименование>", flatName, flat.FlatObject, "edit field", number);
            if (nearestLandmarks != flat.FlatNearestSigns)
                AddRecordChangingStory("Изменение поля <Ближайшие ориентиры>", nearestLandmarks, flat.FlatNearestSigns, "edit field", number);
            if (showTerms != flat.FlatShowTerms)
                AddRecordChangingStory("Изменение поля <Условия показа>", showTerms, flat.FlatShowTerms, "edit field", number);
            if (showTime != flat.FlatShowTime)
                AddRecordChangingStory("Изменение поля <Время показа>", showTime.ToString(), flat.FlatShowTime.ToString(), "edit field", number);
            if (windows != flat.FlatWindowsView)
                AddRecordChangingStory("Изменение поля <Куда выходят окна>", windows, flat.FlatWindowsView, "edit field", number);
            if(price != flat.FinancialData.FinancialDataPriceWithUs) AddRecordChangingStory("Изменение поля <Стоимость>", price.ToString(), 
                flat.FinancialData.FinancialDataPriceWithUs.ToString(),
                "edit field", number);
            if(sellTerms != flat.SellTerms.SellTermsId) AddRecordChangingStory("Изменение поля <Условия продажи>", 
                sellTermsStr, flat.SellTerms.ToString(),
                "edit field", number);
            if(mortgage != flat.FlatMortgage) AddRecordChangingStory("Изменение поля <Ипотека>", 
                mortgage.ToString(), flat.FlatMortgage.ToString(), "edit field", number);
            if (boilerPosition != flat.FlatBoilerPosition) AddRecordChangingStory("Изменение поля <Положение колонки>", 
                boilerPosition, flat.FlatBoilerPosition, "edit field", number);
            if (flat.FlatRoomAppointment != null)
                if (planing != (bool)flat.FlatRoomAppointment) AddRecordChangingStory("Изменение поля <Смежные комнаты>", planing.ToString(),
                                                                                      flat.FlatRoomAppointment.ToString(), "edit field", number);
            if (floor != flat.FlatFloor) AddRecordChangingStory("Изменение поля <Этаж>", floor.ToString(),
                flat.FlatFloor.ToString(), "edit field", number);
            if (maxFloors != flat.FlatFloors) AddRecordChangingStory("Изменение поля <Этажность>", maxFloors.ToString(),
                flat.FlatFloors.ToString(), "edit field", number);
            if (currentDate != flat.FinancialData.FinancialDataDate) AddRecordChangingStory("Изменение поля <Дата>", currentDate.ToString(),
                flat.FinancialData.FinancialDataDate.ToString(), "edit field", number);
            if (contract != flat.FinancialData.FnancialDataContract) AddRecordChangingStory("Изменение поля <Номер договора>", contract.ToString(),
                flat.FinancialData.FnancialDataContract.ToString(), "edit field", number);
            if (source != flat.FinancialData.FinancialDataSource) AddRecordChangingStory("Изменение поля <Номер договора>", source,
                flat.FinancialData.FinancialDataSource.ToString(), "edit field", number);
            if (ownerFIO != flat.Owner.OwnerName) AddRecordChangingStory("Изменение поля <Собственник>", 
                ownerFIO, flat.Owner.OwnerName, 
                "edit field", number);
            if (ownerAdditionalPhone != flat.Owner.OwnerHomePhone) AddRecordChangingStory("Именение поля <Дополнительный теефон собственника>", 
                ownerAdditionalPhone, flat.Owner.OwnerHomePhone,"edit field",number);
            if (howToGetByPublicTransport != flat.FlatHowToGetByPubTransport) AddRecordChangingStory("Именение поля <Как добраться общественным транспортом>",
                howToGetByPublicTransport, flat.FlatHowToGetByPubTransport, "edit field", number);
            if(neighboursCount != flat.FlatNeighboursCount) AddRecordChangingStory("Изменение поля <Количество соседей>", 
                neighboursCount.ToString(), flat.FlatNeighboursCount.ToString(), "edit field", number);
            if (neighboursWithChildrenCount != flat.FlatNeighboursChildrenCount) AddRecordChangingStory("Изменение поля <Количество соседей c детьми>",
                 neighboursWithChildrenCount.ToString(), flat.FlatNeighboursChildrenCount.ToString(), "edit field", number);
            if (newighboursPensioneersCount != flat.FlatNeighboursPensioneersCount) AddRecordChangingStory("Изменение поля <Количество соседей-пенсионеров>",
                 newighboursPensioneersCount.ToString(), flat.FlatNeighboursPensioneersCount.ToString(), "edit field", number);
            if (hasPhone != flat.FlatTelephone) AddRecordChangingStory("Изменение поля <Наличие телефона>",
                 hasPhone.ToString(), flat.FlatTelephone.ToString(), "edit field", number);


            Guid ownerId = flat.FlatOwnerId;
            Guid finDataId = flat.FinancialData.FinancialDataId;

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //var newFlatNewId = AppController.ImmoRepository.AddNewFlat();
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

            AppController.ImmoRepository.EditFinancialData(finDataId, FinDateDate.SelectedDate, price, 
                                                           price, _realtorId, contract, source);
            AppController.ImmoRepository.EditOwner(ownerId, ownerAdditionalPhone, ownerPhone, ownerFIO);

            AppController.ImmoRepository.EditFlat(_flatId, additionalInfo, balconType, address, boilerPosition,
                                                  documentsReady, finDataId, floor,
                                                  maxFloors, houseMaterial, kitchenArea, totalArea, livingArea, flatName,
                                                  currentRegion, mortgage, nearestLandmarks,
                                                  ownerId, additionalInfo, roomCount, roomToSellCount, sellTerms,
                                                  neighboursCount, neighboursWithChildrenCount,
                                                  newighboursPensioneersCount,
                                                  showTerms, showTime, hasPhone, flatType, price,
                                                  (double) price/(double) totalArea, wc, "", windows,
                                                  howToGetByPublicTransport,
                                                  planing, "", _flatNewGuid);
                                                     

            AddRecordChangingStory("Окончание редактирования карточки вторичного жилья", "", "", "edit", number);
        }


        private void BtnAccept_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.AcceptFlat(_flatId, true);

            var newFlat = AppController.ImmoRepository.GetFlatById(_flatId);

            if (newFlat.FlatIsShown != null)
                if ((newFlat.FlatNewId == null)
                    & ((bool)newFlat.FlatIsShown)) //Была добавлена
                {
                    //Все уже сделано! Для различия добавленно записи и редактируемой хватает только хвостового guid, а для различия
                    //с хвостовой записью нужен еще флаг IsShown
                }
                else
                {
                    AppController.ImmoRepository.DeleteFlat(newFlat.FlatNewId); //Удаляем главную запись
                    AppController.ImmoRepository.BreakFlatNewId(newFlat.FlatId); //ОТвязываем
                    AppController.ImmoRepository.SetShownFlat(newFlat.FlatId, true); //Делаем дочернюю запись главной
                }
            AppController.ImmoRepository.DeleteFlat(_flatNewGuid);

            Close();
        }

        private void BtnReject_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.AcceptFlat(_flatId, false);
            var addedNewFlat = AppController.ImmoRepository.GetFlatById(_flatId);

            if (addedNewFlat.FlatNewId == null) //Была добавлена
            {
                AppController.ImmoRepository.DeleteFlat(_flatId);
            }
            else
            {
                AppController.ImmoRepository.DeleteFlat(addedNewFlat.FlatId);
                AppController.ImmoRepository.BreakFlatNewId(addedNewFlat.FlatNewId);
                AppController.ImmoRepository.SetShownFlat(addedNewFlat.FlatNewId, true);
            }

            AppController.ImmoRepository.DeleteFlat(_flatNewGuid);
            Close();
        }

        public void AddRecordChangingStory(string operation, string value, string oldValue, string state, string number)
        {
            AppController.ImmoRepository.AddChangingStory(operation, _flatId, value, oldValue, _realtorId, state, number);
        }

        private void ShowMapBtn_Click(object sender, RoutedEventArgs e)
        {
            var map = new Map();
            if (map.Find(((ComboBoxItem)FlatRegionComboBx.SelectedItem).Content + " " + FlatAddressTBx.Text))
                map.ShowDialog();
            else MessageBox.Show("Не удалось определить местоположение!", "Ошибка определения местоположения");
        }
    }
}
